package code.example.base.exception.oom.heap;

import code.example.tool.FixedThreadPool;

import java.util.concurrent.locks.LockSupport;

/**
 *  可以触发内存溢出的类，生成headdump文件，分析溢出原因
 *
 *  jvm参数：-Xmx100m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D:\logs
 *  -XX:+HeapDumpOnOutOfMemoryError：在内存溢出时输出 headdump日志。
 *  -XX:HumpDumpPath=D:\logs dump文件路径，文件名为：java_pid${进程号}.hprof
 *
 *  输出的文件可以通过visualvm 或 EclipseMemoryAnalyzer 分析
 *
 *  程序运行结果:
 java.lang.OutOfMemoryError: Java heap space
 Dumping heap to D:\logs\java_pid9344.hprof ...
 Heap dump file created [98084663 bytes in 0.095 secs]
 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at code.example.base.exception.oom.OOM.<init>(OOM.java:10)
 at code.example.base.exception.oom.OOM.testOOM(OOM.java:20)
 at code.example.base.exception.oom.OOM.main(OOM.java:24)

 */
public class OOM implements Runnable {
    byte [] data = null;
    public OOM(){
        data = new byte[1024*1024];
    }
    @Override
    public void run() {
        LockSupport.park();
    }

    public static void testOOM(){
        FixedThreadPool fixedThreadPool =  new  FixedThreadPool(1);
        for(int i=0;i<1000;i++){
            fixedThreadPool.execute(new OOM());
        }
    }
    public static void main(String args []){
        OOM.testOOM();
    }

}
